package com.jo.direct;

import com.google.common.collect.Lists;
import com.jo.Config;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * @author Jo
 * @date 2017/12/7
 */
public class Producer {
    public static final String EXCHANGENAME = "direct_exchange";
    public static void main(String[] args) {
        List<String> routingKeys = Lists.newArrayList("error", "info", "debug");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Config.host);
        connectionFactory.setPort(Config.port);
        try {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            //此类型的exchange会忽略routing key,发送信息到所有绑定的queue
            channel.exchangeDeclare(EXCHANGENAME, "direct");
            System.out.println("生产者已成功开启");
            //第一个参数空字符串，代表使用默认的匿名交换器
            for (String routingKey : routingKeys) {
                String msg = "来自" + routingKey + "的消息";
                channel.basicPublish(EXCHANGENAME, routingKey, null, msg.getBytes("utf-8"));
            }
            System.out.println("生产者已生产");
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
